package com.zn.entity;

/**
 * @Description:生成请求行、请求头、请求体
 * @Author: zhangnan
 * @Date: 2019/11/22
 */
public class Response {

    private final String CRLF="\r\n";

    private StringBuilder responseLine = new StringBuilder();
    private StringBuilder responseHeader = new StringBuilder();
    private StringBuilder responseBody = new StringBuilder();

    private String content;

    public Response(String content) {
        this.content = content;
    }

    public Response() { }

    /**
     * 构建响应行
     */
    private void buildResponseLine(int code){

        responseLine.append("HTTP/1.1").append(" ").append(code).append(" ");
        switch(code){
            case 404:
                responseLine.append("NOT FOUND");
                break;
            case 505:
                responseLine.append("SEVER ERROR");
                break;
            case 200:
                responseLine.append("OK");
                break;
        }
        responseLine.append(CRLF);
    }


    /**
     * 构建响应头
     */
    private void buildResponseHeader(String contentType){

        //我们只添加两个必须的响应头，你得告诉我你得内容是什么格式，内容有多长
        responseHeader.append("Content-type:").append(contentType).append(";charset=utf-8").append(CRLF);
//        responseHeader.append("Content-type:""text/html"";charset=utf-8").append(CRLF);
        //正文长度 ：字节长度
        responseHeader.append("Content-Length:").append(content.length()).append(CRLF);
        responseHeader.append(CRLF);
    }

    /**
     * 构建响应体
     */
    private void buildResponseBody(){
        responseBody.append(content);

    }

   public String build(int code,String content,String contentType){
        setContent(content);
        buildResponseLine(code);
        buildResponseHeader(contentType);
        buildResponseBody();
        return responseLine.append(responseHeader).append(responseBody).toString();
   }



    public void setContent(String content) {
        this.content = content;
    }
}
